package io.afu.imagehelper.client;

import io.afu.common.exception.BaseException;
import io.afu.imagehelper.dto.ImgDto;
import io.afu.imagehelper.utils.ImgUtils;
import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImgClient {

    private ImgDto imgDto;

    public ImgDto getImgDto() {
        return imgDto;
    }

    public void setImgDto(ImgDto imgDto) {
        this.imgDto = imgDto;
    }

    public static ImgClient build() {
        return new ImgClient();
    }

    public static  ImgClient build(String imgPath) {
        ImgClient imgClient = new ImgClient();
        imgClient.setImgDto(ImgUtils.getImgDto(imgPath));
        return imgClient;
    }

    public void scale(String toFile,Integer targetWidth) throws BaseException {
        if (this.imgDto == null){
            throw new BaseException("不存在该图片或者该图片有问题无法加载获取图片的大小");
        }
        try {
            double percent = targetWidth.doubleValue() / imgDto.getWidth().doubleValue();
            if (percent>1){
                percent = 1;
            }
            Thumbnails.of(this.imgDto.getFilePath()).scale(percent).toFile(toFile);
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException("图片缩放失败");
        }
    }

    public void scale(String toFile,Double percent) throws BaseException {
        if (this.imgDto == null){
            throw new BaseException("不存在该图片或者该图片有问题无法加载获取图片的大小");
        }
        try {
            Thumbnails.of(this.imgDto.getFilePath()).scale(percent).toFile(toFile);
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException("图片缩放失败");
        }
    }

}
